package com.jhf.youke.gateway.config.filter;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhf.youke.core.entity.Response;
import com.jhf.youke.core.utils.CacheUtils;
import com.jhf.youke.gateway.utils.BaseUtils;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @author RHJ
 */
@Component
@RefreshScope
public class CheckLoginGlobFilter implements GlobalFilter, Ordered {

    @Resource
    ObjectMapper objectMapper;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        var request = exchange.getRequest();
        var path = request.getURI().getPath();

        //检查白名单
        if (BaseUtils.checkWhite(path)) {
            return chain.filter(exchange);
        }

        // 如果没有令牌则拒绝访问
        var authenticationHeader = request.getHeaders().getFirst("token");

        if (StringUtils.isEmpty(authenticationHeader)) {
            return notLogin(exchange.getResponse());
        }
        try {
            String json = CacheUtils.get(authenticationHeader);
            if (StrUtil.isBlank(json)) {
                //未登录
                return notLogin(exchange.getResponse());
            } else {
                //登录成功更新缓存token的时间
                CacheUtils.set(authenticationHeader, json, 2 * 60 * 60);
            }
        } catch (Exception e) {
            return notLogin(exchange.getResponse());
        }
        return chain.filter(exchange);
    }

    @SneakyThrows
    private Mono<Void> notLogin(ServerHttpResponse response) {
        var r = Response.fail(401, "请登录");
        var buffer = response.bufferFactory().wrap(objectMapper.writeValueAsBytes(r));
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return -3;
    }
}

